package mrms.api.web.interceptors;

import lombok.AllArgsConstructor;
import mrms.api.entity.UserEntity;
import mrms.api.repository.DeptRepository;
import mrms.api.repository.UserRepository;
import mrms.api.web.authentication.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author lenchu
 * @date 2019/01/31
 */
@AllArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {
    private final UserRepository userRepository;
    private final JwtUtils jwtUtils;
    private final DeptRepository deptRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("Authorization");
        if (jwt != null) {
            String uid = jwtUtils.getUserIdByJwtString(jwt);
            Optional<UserEntity> userEntity = userRepository.findById(uid);
            if (userEntity.isPresent()) {
                UserEntity u = userEntity.get();
                if (jwtUtils.verifyJwt(jwt, u.getPassword())) {
                    if (u.getPermission() == null) {
                        u.setPermission(u.getDept().getPermission());
                    }
                    request.setAttribute("user", u);
                    return true;
                }
            } else {
                throw new RuntimeException("无效jwt");
            }
        }
        throw new RuntimeException("请先登录");
    }
}
